package com.konsung.ksdc.manager.appmain;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.ProductInfoBean;
import com.konsung.ksdc.bean.netbean.CartDetailNetBean;
import com.konsung.ksdc.bean.netbean.LoopPicNetBean;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.shop.LoopAdapter;
import com.konsung.ksdc.manager.shop.MyOrderActivity;
import com.konsung.ksdc.manager.shop.ProductDetailActivity;
import com.konsung.ksdc.manager.shop.ProductItemAdapter;
import com.konsung.ksdc.manager.shop.ShoppingCartActivity;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import in.srain.cube.views.ptr.PtrClassicDefaultHeader;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.util.PtrLocalDisplay;
import okhttp3.Call;

/**
 * 商城主界面
 * Created by andy on 2017/4/13.
 */
public class ShopFragment extends BaseFragment {
    private static final int MSG_UPDATE_PRODUCT_LIST = 10010; // 更新商品列表
    private static final int MSG_SHOPPING_CART_COUNT = 10000; // 更新购物车数目
    private static final int MSG_SHOPPING_CART_NULL = 10001; // 购物车为空
    private static final int MSG_LOOP_SHOP_UPDATE = 10002; // 更新轮播图数据
    private static final String PRODUCT_ICON_URL = "productIconUrl";
    private static final String PRODUCT_INFO_DATA = "product_info_data";
    private static final int MSG_NO_NETWORK = 10003; // 没有网络
    private static final int MSG_SERVER_ERROR = 10004; // 访问服务器失败

    private SwitchTask mSwitchTask; // 轮播任务
    private LoopAdapter loopAdapter;
    private List<View> viewList = new ArrayList<>(); // 轮播的view
    @Bind(R.id.vp_shop_controller)
    ViewPager vpShopController;
    @Bind(R.id.lv_point_container)
    LinearLayout mPointContainer;
    @Bind(R.id.gv_product_list)
    GridView gvProductList;
    @Bind(R.id.tv_order)
    TextView tvOrder;
    @Bind(R.id.iv_cart)
    ImageView ivCart;
    @Bind(R.id.tv_item_count)
    TextView tvItemCount;
    @Bind(R.id.ll_empty)
    LinearLayout llEmpty;
    @Bind(R.id.btn_go)
    Button btnGo;
    @Bind(R.id.iv_abnormal)
    ImageView ivAbnormal;
    @Bind(R.id.tv_abnormal_type)
    TextView tvAbnormalType;
    @Bind(R.id.tv_abnormal_text)
    TextView tvAbnormalText;
    @Bind(R.id.ptr_refresh)
    PtrFrameLayout ptrRefresh;

    private List<ProductInfoBean> productInfoBeans;
    private List<CartDetailNetBean> cartDetailNetBeans;
    private List<String> picPathList; // 轮播图的图片url地址集合
    private List<String> detailProductList; // 轮播图的商品数据集合
    private ProductItemAdapter adapter;
    private boolean touchOnGridView = false; // 判断手指按下的坐标是否在GridView上
    private int clickItem;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UPDATE_PRODUCT_LIST:
                    if (adapter != null) {
                        adapter.setData(productInfoBeans);
                    } else {
                        adapter = new ProductItemAdapter(getActivity(), productInfoBeans);
                        gvProductList.setAdapter(adapter);
                    }
                    break;
                case MSG_SHOPPING_CART_COUNT:
                    tvItemCount.setVisibility(View.VISIBLE);
                    String text = "+" + String.valueOf(cartDetailNetBeans
                            .size());
                    tvItemCount.setText(text);
                    break;
                case MSG_SHOPPING_CART_NULL:
                    tvItemCount.setVisibility(View.INVISIBLE);
                    tvItemCount.setText("");
                    break;
                case MSG_LOOP_SHOP_UPDATE:
                    // 显示轮播数据
                    loadCarousel();
                    break;
                case MSG_NO_NETWORK:
                    llEmpty.setVisibility(View.VISIBLE);
                    tvItemCount.setVisibility(View.GONE);
                    ivAbnormal.setImageResource(R.drawable.no_wifi);
                    tvAbnormalType.setText(R.string.wifi_not_well);
                    tvAbnormalText.setVisibility(View.VISIBLE);
                    tvAbnormalText.setText(R.string.check_your_network);
                    btnGo.setText(R.string.refresh);
                    break;
                case MSG_SERVER_ERROR:
                    llEmpty.setVisibility(View.VISIBLE);
                    tvItemCount.setVisibility(View.GONE);
                    ivAbnormal.setImageResource(R.drawable.connect_server_fail);
                    tvAbnormalType.setText(R.string.get_data_fail);
                    tvAbnormalText.setVisibility(View.GONE);
                    btnGo.setText(R.string.reload);
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    protected void initEvent() {
        tvOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent(getActivity(), MyOrderActivity.class);
                getActivity().startActivity(intent2);
            }
        });

        ivCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), ShoppingCartActivity.class);
                getActivity().startActivity(intent);
            }
        });

        gvProductList.setOnItemClickListener(new AdapterView
                .OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int
                    position, long id) {
                if (!RequestUtils.checkNetwork(getActivity())) {
                    return;
                }
                ProductInfoBean productInfoBean = (ProductInfoBean) adapter
                        .getItem(position);
                if (productInfoBean != null) {
                    Intent intent = new Intent(getActivity(), ProductDetailActivity.class);
                    String productIconUrl = productInfoBean.getProductIconUrl();

                    intent.putExtra(PRODUCT_INFO_DATA, productInfoBean);
                    intent.putExtra(PRODUCT_ICON_URL, productIconUrl);
                    getActivity().startActivity(intent);
                }
            }
        });

        btnGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initData();
            }
        });
        gvProductList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        touchOnGridView = true;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        touchOnGridView = false;
                        break;
                    default:
                        touchOnGridView = false;
                        break;
                }
                return false;
            }
        });
        vpShopController.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_MOVE) {
                    //当水平移动的时候，禁止刷新
                    ptrRefresh.disableWhenHorizontalMove(true);
                }
                return false;
            }
        });
    }

    /**
     * 初始化商城数据
     */
    private void initData() {
        if (!RequestUtils.checkNetwork(MyApplication.getContext())) {
            handler.sendEmptyMessage(MSG_NO_NETWORK);
            return;
        }
        productInfoBeans = new ArrayList<>();
        if (picPathList == null) {

            picPathList = new ArrayList<>();
        }
        if (detailProductList == null) {

            detailProductList = new ArrayList<>();
        }
        RequestUtils.findAllProducts(new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                handler.sendEmptyMessage(MSG_SERVER_ERROR);
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                if (resultCode.equals(Constants.REQUEST_OK)) {
                    productInfoBeans = responseBean.getList(
                            new TypeToken<List<ProductInfoBean>>() {
                            }.getType());
                    llEmpty.setVisibility(View.GONE);
                    if (productInfoBeans != null) {
                        handler.sendEmptyMessage(MSG_UPDATE_PRODUCT_LIST);
                    }
                }
            }
        });
        initPtr();
    }

    /**
     * 刷新数据
     */
    private void initPtr() {
        /**
         * 经典 风格的头部实现
         */
        final PtrClassicDefaultHeader header = new PtrClassicDefaultHeader(getActivity());
        header.setPadding(0, PtrLocalDisplay.dp2px(15), 0, 0);
        header.setBackgroundResource(R.color.refresh_bg);
        ptrRefresh.setHeaderView(header);
        ptrRefresh.addPtrUIHandler(header);
        ptrRefresh.setPtrHandler(new PtrHandler() {

            //需要加载数据时触发
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptrRefresh.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新数据
                        refreshData();
                    }
                }, 1800);
            }

            /**
             * 检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
             */
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 判断手指按下的坐标是否在GridView上，false则直接刷新
                if (touchOnGridView) {
                    // 判断GridView第一条item是否显示完整，true代表显示完整表示可执行下拉刷新，否则GridView消费下滑事件
                    if (gvProductList.getChildCount() > 0 && gvProductList.getFirstVisiblePosition()
                            == 0 && gvProductList.getChildAt(0).getTop() >= gvProductList
                            .getPaddingTop()) {
                        return true;
                    } else {
                        return false;
                    }
                } else {
                    return true;
                }
            }
        });
    }

    /**
     * 下拉数据刷新
     */
    private void refreshData() {
        // 网络断开
        if (!RequestUtils.checkNetwork(getActivity())) {
            //刷新停止
            ptrRefresh.refreshComplete();
            return;
        }
        RequestUtils.findAllProducts(new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
                ptrRefresh.refreshComplete();
                ToastUtils.toastContent(getActivity(), getString(R.string.update_fail));
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                ptrRefresh.refreshComplete();
                if (resultCode.equals(Constants.REQUEST_OK)) {
                    productInfoBeans = responseBean.getList(
                            new TypeToken<List<ProductInfoBean>>() {
                            }.getType());
                    llEmpty.setVisibility(View.GONE);
                    if (productInfoBeans != null) {
                        handler.sendEmptyMessage(MSG_UPDATE_PRODUCT_LIST);
                    }
                }
            }
        });
        initRollPagerViewData(R.id.content_rb_shop);
    }

    /**
     * 刷新购物车item数目
     */
    public void refreshShopCount() {
        RequestUtils.showCatDetail(NetConfig.currentEmpid, new
                RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {

                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        if (responseBean.getResultCode().equals(Constants
                                .REQUEST_OK)) {
                            cartDetailNetBeans = responseBean.getList(new
                                    TypeToken<List<CartDetailNetBean>>() {
                                    }.getType());
                            if (cartDetailNetBeans != null &&
                                    cartDetailNetBeans.size() > 0) {
                                handler.sendEmptyMessage(MSG_SHOPPING_CART_COUNT);
                            } else {
                                handler.sendEmptyMessage(MSG_SHOPPING_CART_NULL);
                            }
                        }
                    }
                });
    }

    /**
     * 初始化加载轮播图
     */
    private void loadCarousel() {
        // 每次显示清除轮播的子view和动态点
        viewList.clear();
        if (mPointContainer != null) {
            mPointContainer.removeAllViews();
        }

        // 动态添加轮播图片和点
        for (int i = 0; i < picPathList.size(); i++) {
            addPoint(i);
            // 添加图片显示
            addCarouselPic(i);
        }
        loopAdapter = new LoopAdapter(MyApplication.getContext(), viewList);
        vpShopController.setAdapter(loopAdapter);
        // 开启轮播任务
        if (mSwitchTask == null) {
            mSwitchTask = new SwitchTask();
            mSwitchTask.start();
        } else {
            mSwitchTask.start();
        }
        // 给viewpager设置监听
        vpShopController.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int
                    positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                // 监听viewpager滑动，设置不同的点
                int count = mPointContainer.getChildCount();
                for (int i = 0; i < count; i++) {
                    View child = mPointContainer.getChildAt(i);
                    child.setBackgroundResource(i == position ? R.drawable.point_dt_foucs
                            : R.drawable.point_dt_normal);
                }
                vpShopController.setCurrentItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    /**
     * 加载显示轮播图图片
     * @param i item
     */
    private void addCarouselPic(final int i) {
        String url = StringUtils.appendPicPath(picPathList.get(i));
        ImageView view = new ImageView(MyApplication.getContext());
        view.setScaleType(ImageView.ScaleType.FIT_XY);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup
                .LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams
                .MATCH_PARENT));
        Picasso.with(MyApplication.getContext())
                .load(url).networkPolicy(NetworkPolicy.NO_CACHE)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击详情，轮播停止
                if (mSwitchTask != null) {
                    mSwitchTask.stop();
                }
                if (!RequestUtils.checkNetwork(MyApplication.getContext())) {
                    return;
                }
                ProductInfoBean bean = new ProductInfoBean(detailProductList.get(i),
                        detailProductList.get(i), "", "", "");
                Intent intent = new Intent(MyApplication.getContext(),
                        ProductDetailActivity.class);
                String productIconUrl = bean.getProductIconUrl();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(PRODUCT_INFO_DATA, bean);
                intent.putExtra(PRODUCT_ICON_URL, productIconUrl);
                MyApplication.getContext().startActivity(intent);
            }
        });
        viewList.add(view);
    }

    /**
     * 添加点
     * @param i 数据item
     */
    private void addPoint(int i) {
        View point = new View(MyApplication.getContext());
        point.setBackgroundResource(R.drawable.point_dt_normal);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                DensityUtils.dp2px(MyApplication.getContext(), 6),
                DensityUtils.dp2px(MyApplication.getContext(), 6));
        if (i != 0) {

            params.leftMargin = DensityUtils.dp2px(MyApplication
                    .getContext(), 6);
        } else {
            // 第一个时候的左边距为
            point.setBackgroundResource(R.drawable.point_dt_foucs);
        }
        // 添加点
        mPointContainer.addView(point, params);
    }

    /**
     * 轮播图加载子线程
     */
    private class SwitchTask extends Handler implements Runnable {
        @Override
        public void run() {
            // 设置viewpager选中下一个，如果已经是最后一个了，选中第0个
            int item = vpShopController.getCurrentItem();
            if (item == vpShopController.getAdapter().getCount() - 1) {
                // 是最后一个
                item = 0;
            } else {
                item++;
            }
            vpShopController.setCurrentItem(item);
            // 再次执行
            postDelayed(this, 5000);
        }

        /**
         * 轮播图子线程开启
         */
        public void start() {
            removeCallbacks(this);
            postDelayed(this, 2000);
        }

        /**
         * 释放资源
         */
        public void stop() {
            removeCallbacks(this);
        }
    }

    /**
     * 加载广告轮播图的数据
     * @param item item
     */
    public void initRollPagerViewData(int item) {
        // 选择商城的时候才加载数据，否则不加载
        if (item != R.id.content_rb_shop) {
            if (mSwitchTask != null) {
                // 不在商城界面，停止轮播
                mSwitchTask.stop();
            }
            return;
        }
        RequestUtils.findCarouselImages(new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                final List<LoopPicNetBean> loopPicNetBeanList = responseBean
                        .getList(new TypeToken<List<LoopPicNetBean>>() {
                        }.getType());
                // 清空数据
                picPathList.clear();
                detailProductList.clear();
                if (loopPicNetBeanList != null) {
                    for (LoopPicNetBean bean : loopPicNetBeanList) {
                        picPathList.add(bean.getUrl());
                        detailProductList.add(bean.getProductId());
                    }
                    // 刷新数据
                    handler.sendEmptyMessage(MSG_LOOP_SHOP_UPDATE);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        refreshShopCount();
        if (mSwitchTask != null) {
            mSwitchTask.start();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.shop_controller;
    }
}
